<template>
    <el-dialog
        v-model="dialogVisible"
        custom-class="label-dialog-box"
        :title="title"
        width="900px"
        :append-to-body="true"
        :before-close="cancelHandel">
        <div class="el-dialog-body">
            <section class="dialog-content-box">
                <div class="seach">
                    <el-row>
                        <el-col :span="hasConditiion ? 24 : 14">
                            <el-input
                                v-model="dialogData.seachKey"
                                v-debounce="[seachTab]"
                                placeholder="搜索标签组、标签"
                                :prefix-icon="Search" />
                        </el-col>
                        <el-col v-show="!hasConditiion" :span="10" style="text-align: right">
                            <div class="refresh" @click="doRefreshTag">
                                <el-icon class="icon"><refresh-right /></el-icon><span>刷新数据</span>
                            </div>
                            <span>标签不存在？</span>
                            <span class="active" @click="toCreate">
                                <span class="fa fa-edit link-btn" @click="toCreatedLink('')">去创建</span>
                            </span>
                        </el-col>
                    </el-row>
                </div>
                <template v-if="labelList.length > 0">
                    <el-tabs
                        v-if="dialogData.labelType != 0"
                        v-model="dialogData.activeName"
                        type="card"
                        class="label-tabs-box"
                        @tab-change="handleClick">
                        <el-tab-pane
                            v-for="item in labelList"
                            :id="'tab-item-' + item.id"
                            :key="item.id"
                            class="label-list-content"
                            :label="item.name"
                            :name="item.id">
                            <el-scrollbar v-if="item?.list?.length > 0" height="274px" @scroll="pageScroll">
                                <div v-for="itm in item.list" :key="itm.group_id" class="label-list">
                                    <div class="title">{{ itm.group_name }}</div>
                                    <div class="label-item-box">
                                        <div
                                            v-for="(it, ind) in itm.tags"
                                            :key="ind"
                                            :class="{ active: hasChooseDataArr(it) }"
                                            @click="chooseTag(it)">
                                            {{ it.name }}
                                        </div>
                                    </div>
                                </div>
                            </el-scrollbar>
                            <div v-else height="400px">
                                <el-empty image="/static/noData.png" description="暂无数据"></el-empty>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                </template>
                <div v-else height="400px">
                    <el-empty image="/static/noData.png" description="暂无数据"></el-empty>
                </div>
            </section>

            <div class="dialog-content-right">
                <div class="right-title">
                    <div>
                        <span>已选标签</span>
                        <span class="span">({{ chooseDataArr.length }})个</span>
                    </div>
                    <div><span class="active" @click="clearChoose">清空</span></div>
                </div>

                <div class="choose-tag zw-common-scrollbar">
                    <el-tag
                        v-for="tag in chooseDataArr"
                        :key="tag"
                        color="ff6b00"
                        style="margin: 0 5px 5px 0"
                        closable
                        @close="onClose(tag)">
                        {{ tag.name }}
                    </el-tag>
                </div>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <div>
                    <el-button @click="cancelHandel">取消</el-button>
                    <el-button type="primary" @click="submitHandel">保存</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { nextTick, ref, watch, onMounted } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { listGroupType, listTag, listgroupTag, grouplist } from '@/api/customerCenter';
import { listTagNew, groupListTagNew } from '@/api/customer';
import { IsNotEmpty, getSetionId } from '@/utils/utils';
const type = ref(true); //true：数据源为客户标签；false：数据源是客户群标签
const hasConditiion = ref(true); //是否有搜索栏上面的功能
const emit = defineEmits(['save']);
const dialogVisible = ref(false);
const dialogData = ref({});
const labelList = ref([]);
const title = ref('选择标签');
const chooseDataArr = ref<any>([]); //当前选中的标签
let pageParam = { page: 1, page_size: 50 };
let canScroll = true;
let isCreate = false; //当前是否前往创建标签页面了
const initDataFun = (type: number) => {
    dialogData.value = {
        labelChooseType: type == 2 ? 2 : 1, // 1是批量打标签   2 是选择标签
        labelType: type == 2 ? 1 : 3, //3批量打标签  4删除  1 满足任意一个标签  2 同时满足所有标签  0无标签
        labelTypeName: '',
        seachKey: '',
        activeName: 1 //当前标签页
    };
};
// 移除标签
const onClose = (tag: any) => {
    tag.check = !tag.check;
    chooseDataArr.value = chooseDataArr.value.filter(item => item.id != tag.id);
};
// 获取标签组类别列表
const getListGroupType = () => {
    if (type.value) {
        return new Promise((res, ref) => {
            listGroupType()
                .then((r: any) => {
                    res(r);
                })
                .catch((e: any) => {
                    ref(e);
                });
        });
    } else {
        return new Promise((res, ref) => {
            listgroupTag()
                .then((r: any) => {
                    res(r);
                })
                .catch((e: any) => {
                    ref(e);
                });
        });
    }
};

watch(dialogVisible, async val => {
    if (val) {
        isCreate = false; //初始化
        pageParam = {
            page: 1,
            page_size: 50
        };
        loadEndIds.length = 0; // 清空数据已经加载完的的id
        initDataFun(dialogData.value.labelChooseType);
        const groupData = await getListGroupType();
        labelList.value = groupData && groupData.length > 0 ? groupData : [];
        dialogData.value.activeName = labelList.value.length > 0 ? labelList.value[0].id : '';
        getListTagFun();
    }
});

/**
 * 是否在选中的里面存在这一条
 */
const hasChooseDataArr = (tag: any) => {
    return chooseDataArr.value.some(item => item.id == tag.id);
};

/**
 * 刷新数据
 */
const doRefreshTag = () => {
    pageParam = {
        page: 1,
        page_size: 50
    };

    // 清空当前列表
    const currentList: any = labelList.value.find(it => {
        return it.id == dialogData.value.activeName;
    });
    if (currentList) {
        currentList.list?.splice?.(0);
    }
    getListTagFun(true);
};
// 获取标签组内的数据
const getListTagFun: any = isSeach => {
    const index = labelList.value.findIndex(it => {
        return it.id == dialogData.value.activeName;
    });
    if (!labelList.value[index].list) {
        labelList.value[index].list = [];
    }
    if (labelList.value[index].list && labelList.value[index].list.length > 0 && !isSeach) {
        return;
    }
    if (!dialogData.value.activeName) {
        return;
    }
    if (type.value) {
        listTag({
            keyword: dialogData.value.seachKey,
            type_list: dialogData.value.activeName,
            page: pageParam.page,
            page_size: pageParam.page_size
        })
            .then((r: any) => {
                r.data.forEach((item: any) => {
                    item.tags.forEach((itm: any) => {
                        const indx = chooseDataArr.value.findIndex(it => {
                            return it.id == itm.id;
                        });
                        if (indx > -1) {
                            itm.check = true;
                        }
                    });
                });
                // 如果没标签，则当作数据已经加载完毕
                if (!r.data.length) {
                    loadEndIds.push(dialogData.value.activeName);
                }
                labelList.value[index].list.push(...r.data);
                nextTick(() => {
                    canScroll = true;
                });
            })
            .catch((e: any) => {
                canScroll = true;
            });
    } else {
        grouplist({
            keyword: dialogData.value.seachKey,
            // type_list: dialogData.value.activeName,
            type_list: [dialogData.value.activeName],
            page: pageParam.page,
            page_size: pageParam.page_size
        })
            .then((r: any) => {
                r.data.forEach((item: any) => {
                    item.tags.forEach((itm: any) => {
                        const indx = chooseDataArr.value.findIndex(it => {
                            return it.id == itm.id;
                        });
                        if (indx > -1) {
                            itm.check = true;
                        }
                    });
                });
                labelList.value[index].list = r.data;
                nextTick(() => {
                    canScroll = true;
                });
            })
            .catch((e: any) => {
                canScroll = true;
            });
    }
};

onMounted(() => {
    document.addEventListener('visibilitychange', function () {
        //浏览器切换事件
        if (document.visibilityState != 'hidden' && isCreate) {
            getListTagFun();
            isCreate = false;
        }
    });
});

const cancelHandel = () => {
    clearChoose();
    dialogVisible.value = false;
};
// 前往创建
const toCreate = () => {
    isCreate = true;
};

// 数据加载完的id
const loadEndIds: any = [];

// 滚动加载
const pageScroll = (e: any) => {
    const scrollView: any = document.querySelector('#tab-item-' + dialogData.value.activeName + ' .el-scrollbar__view');
    // 如果该条数据已经加载完毕，则不再加载其他数据
    if (loadEndIds.includes(dialogData.value.activeName)) {
        return;
    }
    if (e.scrollTop >= scrollView?.clientHeight - 270 && canScroll) {
        canScroll = false;
        pageParam.page = pageParam.page + 1;
        getListTagFun(true);
    }
};

// 保存数据
const submitHandel = () => {
    const { labelChooseType, labelType } = dialogData.value;
    const idList = chooseDataArr.value.map(it => {
        return it.id;
    });
    if (dialogData.value.labelType != 0) {
        emit('save', { labelChooseType, labelType, data: chooseDataArr.value, idList });
    } else {
        emit('save', { labelChooseType, labelType, data: [], idList: [] });
    }
    dialogVisible.value = false;
};

// 选择选项卡
const handleClick = () => {
    pageParam = {
        page: 1,
        page_size: 50
    };
    getListTagFun();
};

// 选择标签
const chooseTag = (val: any): void => {
    const index = chooseDataArr.value.findIndex((it: any) => {
        return it?.id == val?.id;
    });
    if (index > -1) {
        chooseDataArr.value.splice(index, 1);
    } else {
        chooseDataArr.value.push(val);
    }
};
// 清空选中的标签
const clearChoose = () => {
    chooseDataArr.value.splice(0);
    const keyArr = Object.keys(labelList.value);
    keyArr.forEach((item: string) => {
        if (labelList.value[item].list) {
            labelList.value[item].list.forEach((itm: object) => {
                if (itm.tags && itm.tags.length > 0) {
                    itm.tags.forEach((it: object) => {
                        it.check = false;
                    });
                }
            });
        }
    });

    // 点击右侧清除同时也清空筛选项
    dialogData.value.seachKey = '';
    pageParam = {
        page: 1,
        page_size: 50
    };
    seachTab();
};
const seachTab = async () => {
    const params = { keyword: dialogData.value?.seachKey };
    try {
        const res: any = type.value ? await listTagNew(params) : await groupListTagNew(params);
        const arr: any[] = [];
        res.forEach((item: any) => {
            item.list = type.value ? item.tag_groups : item.group_chat_tag_groups;
            if (IsNotEmpty(item.list)) {
                item.list.forEach((v: any) => {
                    v.group_id = v.type_id;
                    v.group_name = v.name;
                    v.tags = type.value ? v.cust_tag : v.cust_group_tag;
                });
            }
            arr.push(item);
        });
        if (arr.length) dialogData.value.activeName = arr[0].id;

        getSelectLabel(arr); // 回显选中数据
        labelList.value = arr;
    } catch (error) {}
};
// 选中回显
const getSelectLabel = (data: any) => {
    if (chooseDataArr.value.length > 0) {
        const arr = getSetionId('id', chooseDataArr.value);
        data.forEach((item: any) => {
            if (item.list.length > 0) {
                item.list.forEach((v: any) => {
                    if (v?.cust_tag.length > 0) {
                        v?.cust_tag.forEach((k: any) => {
                            if (arr.includes(k?.id)) {
                                k.check = true;
                            }
                        });
                    }
                });
            }
        });
    }
};

const toCreatedLink = (url?: any) => {
    window.open(url || '/customer/tag/manage', '_blank');
};

defineExpose({
    title,
    type,
    dialogVisible,
    hasConditiion,
    dialogData,
    chooseDataArr, //回显的标签数据  {id:***,name:***}
    clearChoose
});
</script>

<style lang="scss" scoped>
.el-dialog-body {
    display: flex;
    .dialog-content-box {
        width: 600px;
        padding-right: 20px;
        .title-box {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            .help_icon {
                cursor: pointer;
                width: 14px;
                height: 14px;
                position: relative;
                left: -24px;
            }
            .right {
                font-size: 14px;
                font-family: STHeitiSC-Light, STHeitiSC;
                color: #969696;
                span {
                    vertical-align: middle;
                }
                .active {
                    color: #ff6b00;
                    cursor: pointer;
                    a {
                        color: #ff6b00;
                        text-decoration: none;
                    }
                }
                .refresh {
                    cursor: pointer;
                    display: inline-block;
                    line-height: 19px;
                    margin-right: 10px;
                    .icon {
                        vertical-align: middle;
                        font-size: 16px;
                    }
                    span {
                        vertical-align: middle;
                    }
                }
                .refresh:hover {
                    color: #ff6b00;
                    .icon {
                        color: #ff6b00;
                    }
                }
            }
        }
        .seach {
            margin-bottom: 20px;
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            color: #969696;
            .el-row {
                display: flex;
                align-items: center;
            }
            span {
                vertical-align: middle;
            }
            .active {
                color: #ff6b00;
                cursor: pointer;
                a {
                    color: #ff6b00;
                    text-decoration: none;
                }
            }
            .refresh {
                cursor: pointer;
                display: inline-block;
                line-height: 19px;
                margin-right: 10px;
                .icon {
                    vertical-align: middle;
                    font-size: 16px;
                }
                span {
                    vertical-align: middle;
                }
                &:hover {
                    color: #ff6b00;
                    .icon {
                        color: #ff6b00;
                    }
                }
            }
        }
        .label-list-content {
            border: solid 1px #eaeaea;
            height: 300px;
            box-sizing: border-box;
            overflow-y: scroll;
            padding: 20px 13px;
            .label-list {
                margin-bottom: 14px;
                .title {
                    font-size: 14px;
                    font-family: STHeitiSC-Light, STHeitiSC;
                    color: #33302d;
                    margin-bottom: 10px;
                }
                .label-item-box {
                    div {
                        display: inline-block;
                        vertical-align: middle;
                        margin-right: 16px;
                        background: #ffffff;
                        border: 1px solid #eaeaea;
                        height: 22px;
                        line-height: 22px;
                        padding: 0 10px;
                        font-size: 14px;
                        font-family: STHeitiSC-Light, STHeitiSC;
                        color: #969696;
                        cursor: pointer;
                        margin-bottom: 10px;
                        &.active {
                            border: 1px solid #ff6b00;
                            color: #ff6b00;
                        }
                    }
                }
            }
        }
        .label-list-content::-webkit-scrollbar {
            display: none;
        }
    }
    .dialog-content-right {
        width: 300px;
        padding: 0px 20px;
        border-left: 1px solid #eaeaea;
        .right-title {
            display: flex;
            justify-content: space-between;
            .active {
                color: #ff6b00;
                cursor: pointer;
            }
        }
        .choose-tag {
            margin-top: 20px;
            max-height: 356px;
            overflow-y: auto;
            overflow-x: hidden;
        }
    }
}

.dialog-footer {
    display: flex;
    justify-content: end;
    align-items: center;
}
</style>
